let utils = require('../../../utils/util.js');
let app = getApp();
Page({

  data: {
    total: 0,
    isloaded: false
  },

  onLoad: function(options) {
    let type = options.type;
    wx.setNavigationBarTitle({
      title: type
    });
    let baseurl = app.globalData.request_baseUrl;
    let url;
    switch (type) {
      case '正在热映':
        url = baseurl + '/v2/movie/in_theaters';
        break;
      case '即将上映':
        url = baseurl + '/v2/movie/coming_soon';
        break;
      case '豆瓣Top250':
        url = baseurl + '/v2/movie/top250';
        break;
    }
    this.data.requestUrl = url;
    this.getMovieList((data) => {
      this.setData({
        movies: data
      });
    })
  },
  // 获取电影列表
  getMovieList(callback) {
    let url = this.data.requestUrl + `?start=${this.data.total}&count=20`;
    utils.http(url, (data) => {
      let transferData = this.transformData(data.subjects);
      callback(transferData);
    });
  }, // 转换数据
  transformData(arr) {
    return arr.map((item) => {
      return {
        id: item.id,
        image_url: item.images.large,
        name: item.title,
        // 分数
        score: item.rating.average,
        // 星星
        stars: +item.rating.stars.slice(0, 1)
      }
    })
  },
  // 上拉加载数据
  onReachBottom() {
    if (this.data.isloaded) return;
    this.data.total = this.data.movies.length;
    wx.showNavigationBarLoading();
    this.getMovieList((data) => {
      wx.hideNavigationBarLoading();
      if (data.length < 　1) {
        this.setData({
          isloaded: true
        });
      }
      this.setData({
        movies: [...this.data.movies, ...data]
      });
    })
  },
  // 下拉刷新数据
  onPullDownRefresh() {
    this.data.total = 0;
    this.setData({
      isloaded: false
    });
    wx.showNavigationBarLoading();
    this.getMovieList((data) => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      this.setData({
        movies: data
      });
    })
  }
})